import logging
from logging.handlers import TimedRotatingFileHandler

from configs.base import BASE_DIR


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'formatter': 'standard',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': f'{BASE_DIR}/logs/server.log',
            'when': 'midnight',
            'backupCount': 20,
        },
        'api': {
            'level': 'DEBUG',
            'formatter': 'standard',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': f'{BASE_DIR}/logs/api.log',
            'when': 'midnight',
            'backupCount': 20,
        },
        'console': {
            'level': 'DEBUG',
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout'
        },
    },
    'loggers': {
        'app.api.socket_tcp': {
            'handlers': ['api'],
            'level': 'DEBUG',
            'propagate': False
        },
        '': {
            'handlers': ['default', 'console'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}


def time_rotating_logger(name, file, backup_count=30, prop=False, level=logging.DEBUG):
    handler = TimedRotatingFileHandler(file, when="midnight", interval=1, backupCount=backup_count)
    handler.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'))
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.propagate = prop
    logger.addHandler(handler)
    return logger
